<?php
/**
 * 删除富文本上传的boskey
 * Author: lyun
 * Date: 2018/2/24
 * Created by Panxsoft.
 */

namespace App\Services\Utils;

class DeleteRichTextBosKey
{
    use Bosable;

    const REGULAR = '/\"http\:\/\/.*?\/toosound-website\/(.*?)\"/'; // 正则表达式

    /**
     *  更新富文本时，删除原来的boskey
     *
     * @param $new_content
     * @param $old_content
     * @return bool
     */
    public function updateRichTextBosKey($new_content, $old_content)
    {
        $new_flag = preg_match_all(self::REGULAR, $new_content, $new_matches);
        $old_flag = preg_match_all(self::REGULAR, $old_content, $old_matches);

        // 如果$old_flag为false 或者$new_content == $old_content return

        if (!$old_flag || ($new_content === $old_content)) return true;

        foreach($old_matches[0] as $key=>$item) {
            if (!in_array($item, $new_matches[0])) {
                // 删除这个boskey的值
                $this->deleteBosKey($old_matches[1][$key]);
            }
        }

        return true;
    }

    /**
     *  删除富文本时，删除原来的boskey
     *
     * @param $content
     * @return bool
     */
    public function deleteRichTextBosKey($content)
    {
        $old_flag = preg_match_all(self::REGULAR, $content, $matches);

        if ($old_flag) {
            foreach($matches[1] as $key=>$item) {
                // 删除这个boskey的值
                $this->deleteBosKey($item);
            }
        }

        return true;
    }
}
